﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

using LeanEngine;
using LeanEngine.Collections;

namespace LeanEngine.Business
{
    /// <summary>
    /// Represents a performance counter category to monitor the system health.
    /// </summary>
    public abstract class DiagnosticCategory
    {
        #region PropertyInfo Members

        /// <summary>
        /// Gets the application name showed on the counter category list.
        /// </summary>
        public abstract string CategoryName { get; }

        /// <summary>
        /// Gets the helper description of the counter category.
        /// </summary>
        public abstract string HelperDescription { get; }

        /// <summary>
        /// Gets the counters list of the category.
        /// </summary>
        public abstract List<DiagnosticCategoryItem> Items { get; }

        #endregion

        #region Static Method Members

        /// <summary>
        /// Verifica se a existe a categoria para o monitoramento da integração.
        /// </summary>
        public static bool Exists(DiagnosticCategory category)
        {
            return PerformanceCounterCategory.Exists(category.CategoryName);
        }

        /// <summary>
        /// Cria o contador de performance no monitorador de performance do windows.
        /// </summary>
        public static void CreateCategory(DiagnosticCategory category)
        {
            if (category.Items.IsNullOrEmpty()) throw new InvalidOperationException("The diagnostic category " + category.CategoryName + " must have unless one category item.");
            if (!PerformanceCounterCategory.Exists(category.CategoryName))
            {
                var counters = new CounterCreationDataCollection();
                var countersList = category.Items.Select(item => new CounterCreationData(item.Name, item.Description, item.CounterType));
                counters.AddRange(countersList.ToArray());

                PerformanceCounterCategory.Create(category.CategoryName, category.HelperDescription, PerformanceCounterCategoryType.SingleInstance, counters);
            }
        }

        /// <summary>
        /// Exclui a categoria do monitorador de performance.
        /// </summary>
        public static void DeleteCategory(DiagnosticCategory category)
        {
            if (PerformanceCounterCategory.Exists(category.CategoryName))
            {
                PerformanceCounterCategory.Delete(category.CategoryName);
            }
        }

        #endregion
    }
}
